package com.lonely.order.utils;

import cn.hutool.core.util.IdUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import com.alibaba.fastjson2.JSON;
import com.lonely.common.exception.BusinessException;
import com.lonely.order.domain.dto.order.SkcStickerQrCodeDTO;
import com.lonely.system.engine.upload.FileUploadFactory;
import com.lonely.system.engine.upload.UploadTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.dromara.pdf.pdfbox.core.base.Document;
import org.dromara.pdf.pdfbox.core.base.Page;
import org.dromara.pdf.pdfbox.core.base.PageSize;
import org.dromara.pdf.pdfbox.core.component.Image;
import org.dromara.pdf.pdfbox.core.component.Rectangle;
import org.dromara.pdf.pdfbox.core.component.*;
import org.dromara.pdf.pdfbox.core.enums.HorizontalAlignment;
import org.dromara.pdf.pdfbox.core.enums.VerticalAlignment;
import org.dromara.pdf.pdfbox.handler.PdfHandler;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.List;
import java.util.Objects;
import java.util.function.Consumer;

/**
 * @author : 黄志标
 * @date: 2025/9/15 16:29
 * @description: 生成打印skc贴纸二维码pdf文件工具类
 */
@Slf4j
public class GeneratorPrintSkcStickerPdfUtil {

    /**
     * 默认生成的二维码宽高
     */
    public static final int QR_CODE_WIDTH = 100;
    public static final int QR_CODE_HEIGHT = 100;

    /**
     * Page 宽高
     */
    public static final int PAGE_WIDTH = 250;
    public static final int PAGE_HEIGHT = 150;

    /**
     * 将二维码对象集合生成pdf，并上传到minio
     *
     * @param skcStickerQrCodes
     * @return
     */
    public static String generatorQrCodePdfAndUploadToMinio(List<SkcStickerQrCodeDTO> skcStickerQrCodes) {

        try (ByteArrayOutputStream pdfOutputStream = new ByteArrayOutputStream()) {
            Document document = PdfHandler.getDocumentHandler().create();

            // 为每个二维码创建一页
            String lastSizeName = skcStickerQrCodes.get(0).getSizeName();
            for (SkcStickerQrCodeDTO skcStickerQrCode : skcStickerQrCodes) {

                if (!Objects.equals(lastSizeName, skcStickerQrCode.getSizeName())) {
                    // 跟上一个尺码不是同一批的尺码， 添加一个提示页
                    Page tipPage = buildTipPage(document);
                    document.appendPage(tipPage);

                    lastSizeName = skcStickerQrCode.getSizeName();
                }

                // 添加二维码页
                document.appendPage(buildQrCodePage(document, skcStickerQrCode));
            }

            // 保存文档
//            document.saveAndClose("C:\\data\\a.pdf");
            document.saveAndClose(pdfOutputStream);

            // 上传到minio
            ByteArrayInputStream pdfFileInputStream = new ByteArrayInputStream(pdfOutputStream.toByteArray());
            String fileName = String.format("%s.pdf", IdUtil.randomUUID());
            String path = FileUploadFactory.getFileUpload(UploadTypeEnum.MINIO).uploadStream(pdfFileInputStream, fileName);
            log.debug("PDF 已成功上传到 MinIO: {}", path);
            return path;
        } catch (Exception e) {
            log.error("生成或上传 PDF 错误: {}", ExceptionUtils.getStackTrace(e));
            throw new BusinessException("生成或上传 PDF 失败");
        }
    }

    /**
     * 构建二维码页
     *
     * @param document
     * @return
     */
    private static Page buildQrCodePage(Document document, SkcStickerQrCodeDTO skcStickerQrCode) {
        // 创建页面
        Page page = new Page(document, PageSize.create(PAGE_WIDTH, PAGE_HEIGHT));

        // 构建当前页数据
        Table table = buildTable(page, skcStickerQrCode);
        table.render();

        return page;
    }

    /**
     * 构建提示页
     *
     * @param document
     * @return
     */
    private static Page buildTipPage(Document document) {
        Page page = new Page(document, PageSize.create(PAGE_WIDTH, PAGE_HEIGHT));
        Table table = new Table(page);
        table.setCellWidths(240);
        table.setHorizontalAlignment(HorizontalAlignment.CENTER);
        table.setVerticalAlignment(VerticalAlignment.CENTER);

        // 添加三行
        table.addRows(buildTipRectangleCell(table, (row) -> row.setIsBorderTop(true)));
        table.addRows(buildTipText(table));
        table.addRows(buildTipRectangleCell(table, (row) -> row.setIsBorderBottom(true)));
        table.render();

        return page;
    }

    /**
     * 构建提示文本
     *
     * @param table
     * @return
     */
    private static TableRow buildTipText(Table table) {
        TableRow tableRow = new TableRow(table);
        tableRow.setHeight(100f); // 设置行高
        tableRow.setIsBorderLeft(true);
        tableRow.setIsBorderRight(true);

        // 文本组件
        Textarea textarea = new Textarea(table.getPage());
        textarea.setText("前后尺码不同,请不要贴错!");
        textarea.setFontSize(16f);
//        textarea.setFontStyle(FontStyle.BOLD);

        TableCell cell = new TableCell(tableRow);
        cell.addComponents(textarea);
        cell.setContentHorizontalAlignment(HorizontalAlignment.CENTER);
        cell.setContentVerticalAlignment(VerticalAlignment.CENTER);
        tableRow.addCells(cell);

        return tableRow;
    }

    /**
     * 构建提示矩形 表格行
     *
     * @param table
     * @param consumer
     * @return
     */
    private static TableRow buildTipRectangleCell(Table table, Consumer<TableRow> consumer) {
        TableRow tableRow = new TableRow(table);
        tableRow.setHeight(20f); // 设置行高
//        tableRow.setIsBorderBottom(true);
        tableRow.setIsBorderLeft(true);
        tableRow.setIsBorderRight(true);
        consumer.accept(tableRow);

        // 创建矩形组件
        Rectangle rectangle2 = new Rectangle(table.getPage());
        rectangle2.setBorderLineWidth(1F);
        rectangle2.setBackgroundColor(Color.GRAY);
        rectangle2.setWidth(230F);
        rectangle2.setHeight(10f);
        rectangle2.setHorizontalAlignment(HorizontalAlignment.CENTER);
        rectangle2.setVerticalAlignment(VerticalAlignment.CENTER);

        // 单元格
        TableCell cell = new TableCell(tableRow);
        cell.addComponents(rectangle2);
        cell.setContentHorizontalAlignment(HorizontalAlignment.CENTER);
        cell.setContentVerticalAlignment(VerticalAlignment.CENTER);
        tableRow.addCells(cell);
        return tableRow;
    }


    /**
     * 构建当前页表格数据
     *
     * @param page
     * @param skcStickerQrCode
     * @return
     */
    private static Table buildTable(Page page, SkcStickerQrCodeDTO skcStickerQrCode) {

        Table table = new Table(page);
        table.setCellWidths(140, 100);
        table.setHorizontalAlignment(HorizontalAlignment.CENTER);
        table.setVerticalAlignment(VerticalAlignment.CENTER);

        // 创建三行
        table.addRows(buildQrCodeTopTableRow(table, skcStickerQrCode)); // 二维码上面行
        table.addRows(buildQrCodeTableRow(table, page, skcStickerQrCode)); // 二维码行
        table.addRows(buildQrCodeBottomTableRow(table, skcStickerQrCode)); // 二维码下面行
        return table;
    }

    /**
     * 构建二维码 下一行表格行对象
     *
     * @param table
     * @param skcStickerQrCode
     * @return
     */
    private static TableRow buildQrCodeBottomTableRow(Table table, SkcStickerQrCodeDTO skcStickerQrCode) {
        TableRow tableRow = new TableRow(table);
        tableRow.setIsBorderBottom(true);
        tableRow.setHeight(20f); // 设置行高

        // 创建左下角文本组件
        tableRow.addCells(buildQrCodeLeftBottomTableCell(table, tableRow, skcStickerQrCode));

        // 创建右下角文本组件
        tableRow.addCells(buildQrCodeRightBottomTableCell(table, tableRow));
        return tableRow;
    }

    /**
     * 构建左下角单元格组件
     *
     * @param table
     * @param tableRow
     * @param skcStickerQrCode
     * @return
     */
    private static TableCell buildQrCodeLeftBottomTableCell(Table table, TableRow tableRow, SkcStickerQrCodeDTO skcStickerQrCode) {
        // 创建左下角文本组件
        Textarea textarea = new Textarea(table.getPage());
        textarea.setText(skcStickerQrCode.getSkc());

        // 创建单元格
        TableCell cell = new TableCell(tableRow);
        cell.addComponents(textarea);
        cell.setContentHorizontalAlignment(HorizontalAlignment.LEFT);
        cell.setContentVerticalAlignment(VerticalAlignment.CENTER);
        cell.setIsBorderLeft(true);
        cell.setContentMarginLeft(5f);
        return cell;
    }


    /**
     * 构建右下角单元格组件
     *
     * @param table
     * @param tableRow
     * @return
     */
    private static TableCell buildQrCodeRightBottomTableCell(Table table, TableRow tableRow) {
        // 创建右下角文本组件
        Textarea rightTextarea = new Textarea(table.getPage());
        rightTextarea.setText("MADE IN CHINA");

        // 创建单元格
        TableCell cell = new TableCell(tableRow);
        cell.addComponents(rightTextarea);
        cell.setContentHorizontalAlignment(HorizontalAlignment.RIGHT);
        cell.setContentVerticalAlignment(VerticalAlignment.CENTER);
        cell.setIsBorderRight(true);
        cell.setContentMarginRight(5f);
        return cell;
    }


    /**
     * 构建二维码 上一行表格行对象
     *
     * @param table
     * @param skcStickerQrCode
     * @return
     */
    private static TableRow buildQrCodeTopTableRow(Table table, SkcStickerQrCodeDTO skcStickerQrCode) {
        TableRow tableRow = new TableRow(table);
        tableRow.setIsBorderTop(true);
        tableRow.setHeight(20f); // 设置行高

        // 创建左上角文本组件
        tableRow.addCells(buildQrCodeLeftTopTableCell(table, tableRow, skcStickerQrCode));

        // 创建右上角文本组件
        tableRow.addCells(buildQrCodeRightTopTableCell(table, tableRow, skcStickerQrCode));
        return tableRow;
    }

    /**
     * 构建左上角单元格组件
     *
     * @param table
     * @param tableRow
     * @param skcStickerQrCode
     * @return
     */
    private static TableCell buildQrCodeLeftTopTableCell(Table table, TableRow tableRow, SkcStickerQrCodeDTO skcStickerQrCode) {
        // 创建左上角文本组件
        Textarea textarea = new Textarea(table.getPage());
        textarea.setText(skcStickerQrCode.getProduceOrderId());

        // 创建单元格
        TableCell cell = new TableCell(tableRow);
        cell.addComponents(textarea);
        cell.setContentHorizontalAlignment(HorizontalAlignment.LEFT);
        cell.setContentVerticalAlignment(VerticalAlignment.CENTER);
        cell.setIsBorderLeft(true);
        cell.setContentMarginLeft(5f);
        return cell;
    }

    /**
     * 构建右上角单元格组件
     *
     * @param table
     * @param tableRow
     * @param skcStickerQrCode
     * @return
     */
    private static TableCell buildQrCodeRightTopTableCell(Table table, TableRow tableRow, SkcStickerQrCodeDTO skcStickerQrCode) {
        // 创建右上角文本组件
        Textarea rightTextarea = new Textarea(table.getPage());
        rightTextarea.setText(skcStickerQrCode.getSizeName());

        // 创建单元格
        TableCell cell = new TableCell(tableRow);
        cell.addComponents(rightTextarea);
        cell.setContentHorizontalAlignment(HorizontalAlignment.RIGHT);
        cell.setContentVerticalAlignment(VerticalAlignment.CENTER);
        cell.setIsBorderRight(true);
        cell.setContentMarginRight(5f);
        return cell;
    }


    /**
     * 构建二维码行
     *
     * @param table
     * @param page
     * @param skcStickerQrCode
     * @return
     */
    private static TableRow buildQrCodeTableRow(Table table, Page page, SkcStickerQrCodeDTO skcStickerQrCode) {
        TableRow tableRow = new TableRow(table);
        // 设置行高
        tableRow.setHeight(100f);

        // 创建单元格
        TableCell cell = new TableCell(tableRow);
        // 设置合并列数
        cell.setColspan(1);
        // 添加组件
        BufferedImage qrImage = createQrCodeImage(JSON.toJSONString(skcStickerQrCode));
        Image image = buildImage(page, qrImage);
        cell.addComponents(image);


        cell.setContentHorizontalAlignment(HorizontalAlignment.CENTER);
        cell.setContentVerticalAlignment(VerticalAlignment.CENTER);
        cell.setIsBorderLeft(true);
        cell.setIsBorderRight(true);

        // 添加单元格
        tableRow.addCells(cell);
        return tableRow;
    }


    /**
     * 构建图片组件
     *
     * @param page
     * @param qrImage
     * @return
     */
    private static Image buildImage(Page page, BufferedImage qrImage) {
//        Image image = new Image(document.getCurrentPage());
        Image image = new Image(page);
        // 设置图像
        image.setImage(qrImage);
        // 设置宽度
        image.setWidth(QR_CODE_WIDTH);
        // 设置高度
        image.setHeight(QR_CODE_HEIGHT);
        image.setHorizontalAlignment(HorizontalAlignment.CENTER); // 设置水平居中
        image.setVerticalAlignment(VerticalAlignment.CENTER); // 设置垂直居中
        return image;
    }


    /**
     * 生成二维码Image对象
     *
     * @param qrCodeBody
     * @return
     */
    private static BufferedImage createQrCodeImage(String qrCodeBody) {
        try {
            return QrCodeUtil.generate(qrCodeBody, QR_CODE_WIDTH, QR_CODE_HEIGHT);
        } catch (Exception e) {
            log.error("生成二维码失败: {}", ExceptionUtils.getStackTrace(e));
            throw new BusinessException("生成二维码失败");
        }
    }


}
